<template>
  <div class="node">
    <div>
      <el-card class="content-card" shadow="never">
        <el-row class="tab-header">
          <div>
            <el-button disabled icon="Edit" type="primary" />
          </div>
          <div>
            <el-input
              v-model="searchQuery.name"
              class="node-head-search"
              clearable
              placeholder="请输入"
            />
            <el-button
              icon="Search"
              type="primary"
              circle
              @click="getNodes()"
            />
            <el-button icon="Refresh" circle @click="getNodes()" />
          </div>
        </el-row>
        <el-table
          v-loading="loading"
          style="width: 100%; font-size: 12px; margin-bottom: 10px"
          :data="nodeList"
        >
          <el-table-column width="20" />
          <el-table-column align="left" label="Node名">
            <template v-slot="scope">
              <p class="node-body-nodename">
                <el-button
                  text
                  type="primary"
                  @click="showNodeDetails(scope.row?.metadata?.name)"
                >
                  {{ scope.row.metadata.name }}
                </el-button>
              </p>
              <p class="node-body-ip">
                {{ scope.row.status.addresses[0].address }}
              </p>
            </template>
          </el-table-column>
          <el-table-column align="center" label="规格">
            <template v-slot="scope">
              <el-tag type="warning"
                >{{ scope.row.status.capacity.cpu }}核{{
                  specTrans(scope.row.status.capacity.memory)
                }}G</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column align="center" label="POD-CIDR">
            <template v-slot="scope">
              <span>{{ scope.row.spec.podCIDR }} </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="版本">
            <template v-slot="scope">
              <span>{{ scope.row.status.nodeInfo.kubeletVersion }} </span>
            </template>
          </el-table-column>
          <el-table-column align="center" min-width="100" label="创建时间">
            <template v-slot="scope">
              <el-tag type="info"
                >{{ timeTrans(scope.row.metadata.creationTimestamp) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="120">
            <template v-slot="scope">
              <el-button
                size="small"
                style="border-radius: 2px"
                icon="Edit"
                type="primary"
                plain
                @click="getNodeDetails(scope)"
                >YAML</el-button
              >
              <el-button
                size="small"
                style="border-radius: 2px"
                icon="Document"
                type="warning"
                plain
                @click="showNodeDetails(scope.row?.metadata?.name)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="node-body-pagination"
          background
          :current-page="pager.currentPage.value"
          :page-sizes="pager.limitList.value"
          :page-size="pager.limit.value"
          layout="total, sizes, prev, pager, next, jumper"
          :total="nodeTotal"
        />
      </el-card>
    </div>
    <el-dialog v-model="yamlDialog" title="YAML信息" width="45%" top="5%">
      <codemirror
        :value="srcYamlContent"
        border
        :options="cmOptions"
        height="500"
        style="font-size: 14px"
        @change="onChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="yamlDialog = false">取 消</el-button>
          <el-button disabled type="primary" @click="updateNode()"
            >更 新</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- <NodeInfo ref="nodeInfoViewer" /> -->
  </div>
</template>

<script setup lang="ts">
import { ElMessageBox } from "element-plus";
import provider from "./nodeProvider";
import common from "../common/Config";
import { onMounted, ref } from "vue";
import { timeTrans } from "@/views/domain/kubeHud/utils";

import { useProvider } from "../provider";
import { useRouter } from "vue-router";

const { jumpToRoutePath } = useProvider();
const router = useRouter();

const { cmOptions } = common;
const {
  getNodes,
  getNodeDetails,
  updateNode,
  deleteNode,
  yamlDialog,
  srcYamlContent,
  nodeTotal,
  loading,
  nodeList,
  searchQuery,
  pager,
  nodeApi
} = provider;

const onChange = val => {
  srcYamlContent.value = val;
};

const specTrans = str => {
  if (str.indexOf("Ki") == -1) {
    return str;
  }
  let num = str.slice(0, -2) / 1024 / 1024;
  return num.toFixed(0);
};

const handleConfirm = (cbArg: any, msg: string, cb: (any) => void) => {
  ElMessageBox.confirm(`确定要${msg}吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      cb(cbArg);
    })
    .catch(() => {});
};

const nodeInfoViewer = ref();

const showNodeDetails = (name?: string) => {
  // jumpToRoutePath("/cluster/nodeDetails", { name });
  router.push({ name: "NodeDetails", query: { name } });
};

onMounted(() => {
  getNodes();
});

/*
export default {
  data() {
    return {
      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: "",
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      //
      searchInput: "",
      namespaceValue: "default",
      namespaceList: [],
      appLoading: false,
      nodeList: [],
      nodeTotal: 0,
      getNodesData: {
        params: {
          filter_name: "",
          namespace: "",
          page: "",
          limit: ""
        }
      },
      //详情
      nodeDetail: {},
      getNodeDetailData: {
        params: {
          name: "",
          namespace: ""
        }
      },
      //yaml更新
      yamlDialog: false,
      updateNodeData: {
        params: {
          namespace: "",
          content: ""
        }
      },
      //删除
      delNodeData: {
        params: {
          name: "",
          namespace: ""
        }
      }
    };
  },
  beforeMount() {
    this.getNodes();
  },
  methods: {
    transYaml(content) {
      return json2yaml.stringify(content);
    },
    transObj(content) {
      return yaml2obj.load(content);
    },
    onChange(val) {
      this.contentYaml = val;
    },
    handleSizeChange(size) {
      this.pagesize = size;
      this.getNodes();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getNodes();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    ellipsis(value) {
      return value.length > 15 ? value.substring(0, 15) + "..." : value;
    },
    timeTrans(timestamp) {
      let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000);
      date = date.toJSON();
      date = date.substring(0, 19).replace("T", " ");
      return date;
    },
    specTrans(str) {
      if (str.indexOf("Ki") == -1) {
        return str;
      }
      let num = str.slice(0, -2) / 1024 / 1024;
      return num.toFixed(0);
    },
    getNamespaces() {
      getNamespecelist()
        .then(res => {
          this.namespaceList = res.data.items;
        })
        .catch(res => {
          this.$message.error({
            message: res.msg
          });
        });
    },
    getNodes() {
      this.appLoading = true;
      this.getNodesData.params.filter_name = this.searchInput;
      this.getNodesData.params.page = this.currentPage;
      this.getNodesData.params.limit = this.pagesize;
      getNodeList(this.getNodesData.params)
        .then(res => {
          this.nodeList = res.data.items;
          this.nodeTotal = res.data.total;
        })
        .catch(res => {
          this.$message.error({
            message: res.msg
          });
        });
      this.appLoading = false;
    },
    getNodeDetail(e) {
      this.getNodeDetailData.params.name = e.row.metadata.name;
      this.getNodeDetailData.params.namespace = this.namespaceValue;
      GetNodeDetail(this.getNodeDetailData.params)
        .then(res => {
          this.nodeDetail = res.data;
          this.contentYaml = this.transYaml(this.nodeDetail);
          this.yamlDialog = true;
        })
        .catch(res => {
          this.$message.error({
            message: res.msg
          });
        });
    },
    updateNode() {
      let content = JSON.stringify(this.transObj(this.contentYaml));
      this.updateNodeData.params.namespace = this.namespaceValue;
      this.updateNodeData.params.content = content;
      UpdateNode(this.updateNodeData.params)
        .then(res => {
          this.$message.success({
            message: res.msg
          });
        })
        .catch(res => {
          this.$message.error({
            message: res.msg
          });
        });
      this.yamlDialog = false;
    },
    delNode(e) {
      this.delNodeData.params.name = e.row.metadata.name;
      this.delNodeData.params.namespace = this.namespaceValue;
      DeleteNode(this.delNodeData.params)
        .then(res => {
          this.getNodes();
          this.$message.success({
            message: res.msg
          });
        })
        .catch(res => {
          this.$message.error({
            message: res.msg
          });
        });
    },
    handleConfirm(obj, operateName, fn) {
      this.confirmContent = "确认继续 " + operateName + " 操作吗？";
      this.$confirm(this.confirmContent, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          fn(obj);
        })
        .catch(() => {
          this.$message.info({
            message: "已取消操作"
          });
        });
    }
  }
};
*/
</script>

<style scoped lang="scss">
.node-head-card,
.node-body-card {
  border-radius: 1px;
  margin-bottom: 5px;
}
.node-head-search {
  width: 160px;
  margin-right: 10px;
}
.node-body-nodename {
  margin: 0px;
  color: #4795ee;
}
.node-body-ip {
  margin: 0px;
  color: rgb(145, 145, 145);
}
.node-body-nodename:hover {
  color: rgb(84, 138, 238);
  cursor: pointer;
  font-weight: bold;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.content-card {
  border: none !important;
  --el-card-padding: 10px;
}
</style>
